﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Data;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.DAL.DTOs;
using System.IO;
using System.Globalization;

namespace MS.InformationManagement.BLL.GuiasDeEnvio
{
    public class GuiasDeEnvio
    {
        public static List<RadicadoSearchDTO> SearchInLibrary()
        {
            List<RadicadoSearchDTO> itemsFound = new List<RadicadoSearchDTO>();
            SPSiteDataQuery q = new SPSiteDataQuery();
            q.ViewFields = "<FieldRef Name='" + CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE + @"' /><FieldRef Name='" + CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN_ID + @"' /><FieldRef Name='ContentType' /><FieldRef Name='Document_SendDest'/><FieldRef Name='ServerUrl'/><FieldRef Name='" + CustomSiteColumns.FIELD_DOCUMENT_RADICADOR + "' /><FieldRef Name='" + CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID + "' /><FieldRef Name='" + CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID + "' /><FieldRef Name='" + CustomSiteColumns.FIELD_DOCSET_DEPARTMNET + "' />";
            q.Lists = "<Lists BaseType='1'/>";
            q.Webs = "<Webs Scope='SiteCollection' />"; 
            // GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA
            //GlobalConstants.CTTN_RADICADO_EMPRESA_SALIDA
            q.Query += @"<Where>
									<And>
										<Or>
											<Eq>
												<FieldRef Name='ContentType'/>
												<Value Type='Computed'>Radicado Persona Salida</Value>
											</Eq>
											<Eq>
												<FieldRef Name='ContentType'/>
												<Value Type='Computed'>Radicado Empresa Salida</Value>
											</Eq>
										</Or>
										<IsNull>
											<FieldRef Name='Document_Shipping_Guide' />
										</IsNull>
									</And>
								</Where>";

            DataTable dt = null;
            using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb web = currentSite.OpenWeb())
                {
                    dt = web.GetSiteData(q);
                }
            }
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty((dr[CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE] + "").Trim()))
                {
                    string EsCorreoCertificado = dr[CustomSiteColumns.FIELD_DOCUMENT_DELIVERY_MEAN_ID] + "";
                    if (!string.IsNullOrEmpty(EsCorreoCertificado))
                    {
                        if (LoadMediosDeEnvio(EsCorreoCertificado) == true)
                        {
                            string radicador = dr[CustomSiteColumns.FIELD_DOCUMENT_RADICADOR] + "";
                            if (!string.IsNullOrEmpty(radicador))
                            {

                                SPUser userOwnerRadicado = SPContext.Current.Web.EnsureUser(radicador);
                                RadicadoSearchDTO radicados = new RadicadoSearchDTO();
                                radicados.Id = dr["ID"].ToString();
                                radicados.IdList = dr["ListId"].ToString();
                                radicados.CurrentUser = userOwnerRadicado.Name;
                                radicados.IdExpediente = dr[CustomSiteColumns.FIELD_DOCUMENT_EXPEDIENTE_ID] + "";
                                radicados.IdRadicado = dr[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID] + "";
                                radicados.Department = MS.InformationManagement.BLL.BusquedaPrestamosDocumentales.BusquedaPrestamosDocumentales.GetDepartamento(dr[CustomSiteColumns.FIELD_DOCSET_DEPARTMNET].ToString());
                                itemsFound.Add(radicados);
                            }
                        }
                    }
                }
            }
            

            return itemsFound;
        }

        public static bool UploadShippingGuide(List<RadicadoSearchDTO> Guias)
        {
            bool result = true;

            foreach (RadicadoSearchDTO rad in Guias)
            {
                int IdShippingGuide = UploadDocuement(rad);
                if (IdShippingGuide!=0)
                    result = UpdateShippingGuideField(int.Parse(rad.Id), new Guid(rad.IdList), int.Parse(rad.IdGuia));
            }
            

            return result;
        }

        private static int UploadDocuement(RadicadoSearchDTO radicado)
        {
            int result = 0;
            String documentLibraryName = GlobalConstants.LIST_GUIAS_DE_ENVIO;

            using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    oWeb.AllowUnsafeUpdates = true;
                    SPList myList = oWeb.Lists[documentLibraryName];
                    SPFolder myLibrary = myList.RootFolder;
                    Byte[] array = new Byte[1];                    
                    Boolean replaceExistingFiles = true;
                    SPFile spfile = myLibrary.Files.Add(Guid.NewGuid() + ".txt", array, replaceExistingFiles);
                    spfile.Update();

                    SPItem newItem = spfile.Item;
                    newItem[CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE] = radicado.IdGuia;
                    newItem.Update();
                    myLibrary.Update();
                    myList.Update();

                    oWeb.AllowUnsafeUpdates = false;

                    result = newItem.ID;
                }
            }

            return result;
        }

        private static bool UpdateShippingGuideField(int idItem, Guid TargetLibrary, int IdShippingGuide)
        {
            bool result = false;

            var spFolder = SPContext.Current.Web.Lists[TargetLibrary].GetItemById(idItem).Folder;
            spFolder.Item.Update();
            string Document_Shipping_Guide = spFolder.Item[CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE] +"";
            if (string.IsNullOrEmpty(Document_Shipping_Guide.Trim()))
            {
                spFolder.Item[CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE] = IdShippingGuide+"";
            }
            else
            {
                spFolder.Item[CustomSiteColumns.FIELD_DOCUMENT_SHIPPING_GUIDE] = Document_Shipping_Guide + ";" + IdShippingGuide;
            }            
            spFolder.Item.Update();
            result = true;

            return result;
        }

        public static bool? LoadMediosDeEnvio(string idMedioEnvio)
        {
            bool? result = false;
            int id = (int)double.Parse(idMedioEnvio, CultureInfo.InvariantCulture);
            using (DCDocumentCenterDataContext dx = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var foundMedios = (from medios in dx.MediosDeEnvio
                                   where medios.Id == id
                               orderby medios.Title ascending
                               select medios).FirstOrDefault();
                if (foundMedios != null)
                    result = foundMedios.EsCorreoCertificado;
            }
            return result;
        }
    }
}
